import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import LazyComponent from '@/components/LazyComponent';
import { isMobile } from '@/utils/tools/browser_utls';
import { LazyFn } from '@/components/LazyComponent/type';
import NoMatch from '../components/Layout/404';
import routerData from './routerData'; // 路由配置
import PrivateRoute from './PrivateRoute';
import ErrorBoundary from './ErrorBoundary';

const isH5Flag = isMobile();

export interface RouterItem {
  path: string;
  name?: string;
  title?: string;
  parentPath?: string;
  redirect?: string;
  exact?: boolean;
  meta?: {
    label?: string;
    role?: string;
    hide?: boolean;
    needLogin?: boolean;
  };
  component?: LazyFn;
  componentPc?: LazyFn;
  componentH5?: LazyFn;
}

export type IRoutersData = RouterItem[];

export interface RoutersState {
  routers?: IRoutersData;
}

/** 路由生成处理 */
export const interceptorRoute = (item: RouterItem) => {
  if (item.redirect) {
    return (
      <Route
        path={item.path}
        render={() => <Redirect to={item.redirect || ''} />}
        exact
        key={item.path}
      />
    );
  }

  let newComponent = item.component;
  if (!item.component) {
    newComponent = isH5Flag ? item.componentH5 : item.componentPc;
  }

  const Page = LazyComponent(newComponent);

  return (
    <PrivateRoute
      exact={item.exact !== false}
      meta={item.meta || {}}
      title={item.title}
      key={item.path}
      path={item.path}
      redirect={item.redirect}
      component={Page}
    />
  );
};

class Routers extends React.Component<any, RoutersState> {
  constructor(props) {
    super(props);
    this.state = {
      routers: routerData || [],
    };
  }

  render() {
    const { routers } = this.state;
    return (
      <ErrorBoundary>
        <Switch>
          {routers?.map((item) => {
            return interceptorRoute(item);
          })}
          <Route component={NoMatch} key="noMatch" />
        </Switch>
      </ErrorBoundary>
    );
  }
}

export default Routers;
